package com.zkingsoft.zkingbase.model;

import android.text.TextUtils;

import com.zkingsoft.zkingbase.bean.User;
import com.zkingsoft.zkingbase.bean.resp.BaseResp;
import com.zkingsoft.zkingbase.bean.resp.MapInfoBean;
import com.zkingsoft.zkingbase.presenter.UserLoginPresenter;
import com.zkingsoft.zkingbase.view.ILoginView;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.http.POST;
import retrofit2.http.Query;

/**
 * Created by ytf on 2017/3/7 007.
 * Description:
 */

public class UserLoginModel extends BaseModel
{
    private LoginService service;

    public void login(String phone,String password, UserLoginPresenter<ILoginView, User> presenter)
    {
        if(TextUtils.isEmpty(phone) || TextUtils.isEmpty(password))
            return;
        service = retrofit.create(LoginService.class);
        observable = service.loginByPhone(phone, password);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResp>()
                {
                    @Override
                    public void onSubscribe(Disposable d)
                    {
                        //流式设计，此处主要用于拿到disposable
                        dis = d;
                        //onStart用于显示开始等待框
                        presenter.onStart();
                    }

                    @Override
                    public void onNext(BaseResp value)
                    {
                        //登录业务逻辑
                        MapInfoBean mi = value.mapInfo;
                        if(mi != null)
                        {
                            User u = mi.user;
                            if(u != null)
                            {
                                presenter.onSuccess(u, null);
                                dispose();
                            }
                        }else
                        {
                            presenter.onFailed(value.info, new Throwable("error"));
                        }

                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        presenter.onFailed(getFailedString(e), e);
                        dispose();
                    }

                    @Override
                    public void onComplete()
                    {
                        presenter.onComplete();
                        dispose();
                    }
                });
    }

    public interface LoginService
    {
        @POST("user/dologin?")
        Observable<BaseResp> loginByPhone(@Query("suTel") String phone, @Query("suPassword") String password);
    }
}
